package com.android.clinic.app.ui.doctor;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.adapter.GridImageAdapter;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.picture.bean.FunctionConfig;
import com.android.clinic.app.picture.bean.LocalMedia;
import com.android.clinic.app.picture.bean.LocalMediaLoader;
import com.android.clinic.app.picture.bean.PictureConfig;
import com.android.clinic.app.ui.widget.FullyGridLayoutManager;
import com.android.clinic.app.utils.BaseTextWatcher;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.LocalDataUtils;
import com.jiongbull.jlog.JLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by cheng on 2018/2/5.
 * 向某医生提问(诊后咨询)
 */
public class AskQuestionWithDoctorActivity extends BaseActivity {

    private EditText etQuestion, etArea;
    private String imgUrl, doctorId = "";

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ask_question_with_doctor;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("提问");
        setTitleBarLeftResource(R.drawable.icon_back);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();

        doctorId = this.getIntent().getStringExtra("doctorId");
        JLog.e("doctorId:-- " + doctorId);

        etQuestion = (EditText) findViewById(R.id.et_question);
        etArea = (EditText) findViewById(R.id.et_area);

        etQuestion.addTextChangedListener(new AskTextWatcherListener());

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(AskQuestionWithDoctorActivity.this,
                4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(AskQuestionWithDoctorActivity.this,
                onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(FunctionConfig.SELECT_MAX_NUM);
        recyclerView.setAdapter(adapter);

    }

    @Override
    protected void onBackClickListener(View v) {
        saveCacheQuestionID();
    }

    @Override
    public void onBackPressed() {
        saveCacheQuestionID();
    }

    /**
     * 当用户没有给医生发起提问，点击返回时，缓存当前的医生信息，以便再次进入医生详情时弹出提示
     */
    private void saveCacheQuestionID() {
        if (!TextUtils.isEmpty(doctorId)) {
            LocalDataUtils.saveData(Constants.QUESTION_ID, doctorId);
        }
        finish();
    }

    private class AskTextWatcherListener extends BaseTextWatcher {

        private CharSequence temp;
        private int editStart;
        private int editEnd;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            temp = s;
        }

        @Override
        public void afterTextChanged(Editable editable) {
            editStart = etQuestion.getSelectionStart();
            editEnd = etQuestion.getSelectionEnd();
            if (temp.length() > 500) {//限制长度
                showToast("输入的字数已经超过了限制！");
                editable.delete(editStart - 1, editEnd);
                int tempSelection = etQuestion.length();
                etQuestion.setText(editable);
                etQuestion.setSelection(tempSelection);
            }
        }
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @Override
        public void onAddPicClick() {
            FunctionConfig config = new FunctionConfig();
            config.setType(LocalMediaLoader.TYPE_IMAGE); // 图片 or 视频
            config.setCopyMode(FunctionConfig.COPY_MODEL_DEFAULT); // 裁剪比例，默认、1:1、3:4、3:2、16:9
            config.setCompress(true);  // 是否压缩图片
            config.setEnablePixelCompress(true);  // 是否启用像素压缩
            config.setEnableQualityCompress(true); // 是否启用质量压缩
            config.setMaxSelectNum(FunctionConfig.SELECT_MAX_NUM);  // 可选择图片的数量
            config.setSelectMode(FunctionConfig.MODE_MULTIPLE);  // 单选 or 多选
            config.setShowCamera(true);   // 是否显示拍照
            config.setEnablePreview(true); // 是否打开预览选项
            config.setImageSpanCount(4);  // 每行显示个数
            config.setSelectMedia(selectList);
            // 先初始化参数配置，在启动相册
            PictureConfig.init(config);
            PictureConfig.getPictureConfig().openPhoto(AskQuestionWithDoctorActivity.this, resultCallback);
        }
    };

    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList, String path) {
            imgUrl = path;
            selectList = resultList;
            adapter.setList(selectList);
            adapter.notifyDataSetChanged();
        }
    };

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        if (v.getId() == R.id.btn_send_to_doctor) {
            String description = etQuestion.getText().toString().trim();
            String area = etArea.getText().toString().trim();
            if (description.length() == 0) {
                showToast("请输入您提问的内容!");
                return;
            } else if(area.length() == 0) {
                showToast("请输入地区!");
                return;
            }

            if (!TextUtils.isEmpty(doctorId)) {
                HttpClient.getHttpService().sendInquireInfo(ClinicApplication.getUserInfo().getId(),
                        doctorId, description, imgUrl, area)
                        .compose(this.bindToLifecycle())
                        .compose(RxObservableUtils.applySchedulers())
                        .subscribe(new BaseObserver<String>() {
                            @Override
                            public void onSuccess(String s) {
                                LocalDataUtils.removeData(Constants.QUESTION_ID);
                                showToast("问题已提交，请您耐心等待医生的回复!");
                                finish();
                            }

                            @Override
                            public void onFailure(String message) {
                                showToast(message);
                            }
                        });
            } else {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("area", area);
                    jsonObject.put("description", description);
                    jsonObject.put("imgUrl", imgUrl);
                    jsonObject.put("userId", ClinicApplication.getUserInfo().getId());

                    MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
                    RequestBody body = RequestBody.create(jsonType, jsonObject.toString());

                    HttpClient.getHttpService().sendDoctorRecommend(body)
                            .compose(this.bindToLifecycle())
                            .compose(RxObservableUtils.applySchedulers())
                            .subscribe(new BaseObserver<String>() {
                                @Override
                                public void onSuccess(String s) {
                                    showToast("您的咨询已提交，管家会尽快与您联系!");
                                    finish();
                                }

                                @Override
                                public void onFailure(String message) {
                                    showToast(message);
                                }
                            });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
